<?php
namespace app\controller;

# 如果使用的类命名空间和现命名空间一致，可不用再次use
use dxing\Controller;
use dxing\Model;
use dxing\Config;
use dxing\Log;
use app\model\LangModel;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExcelController extends Controller{

    public function index(){
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // $sheet->setCellValue('A1', 'Hello World !');
        $sheet->setCellValue('A1', 'Hello World');
        $sheet->setCellValue('B1', 'World');

        $writer = new Xlsx($spreadsheet);
        $writer->save('Test.xlsx');
    }

    /**根据提交的时间导出数据**/
    public function outdata(){
        $start=strtotime(input('post.outstart')); /**将日期转换成时间戳**/
        $end=strtotime(input('post.outend'));/**将日期转换成时间戳**/

        if(empty($start)||empty($end)){ /**如果时间为空 查询所有数据**/
            $data=Db::table('fs_hk666')->order('id desc')->select();
        }else{  /**根据时间查询数据**/
            $data=Db::table('fs_hk666')->whereTime('create_time', 'between', [$start, $end])->order('id desc')->select();/**传递分页参数**/
        }

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'id编号');
        $sheet->setCellValue('B1', '姓名');
        $sheet->setCellValue('C1', '手机号码');
        $sheet->setCellValue('D1', '来源');
        $sheet->setCellValue('E1', '来源ip');
        $sheet->setCellValue('F1', '入库时间');

        /*--------------开始从数据库提取信息插入Excel表中------------------*/
         $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
         /*$i = 2,因为第一行是表头，所以写到表格时候只能从第二行开始写。*/
        $count = count($data);  //计算有多少条数据
        for ($i = 2; $i <= $count+1; $i++) {
            $sheet->setCellValue('A' . $i, $data[$i-2]['id']);
            $sheet->setCellValue('B' . $i, $data[$i-2]['name']);
            $sheet->setCellValue('C' . $i, $data[$i-2]['mobile']);
            if($data[$i-2]['status']=='0'){
                $sheet->setCellValue('D' . $i,"电脑");
            }else{
                $sheet->setCellValue('D' . $i,"移动");
            }
            $sheet->setCellValue('E' . $i, $data[$i-2]['from_ip']);
            $sheet->setCellValue('F' . $i, date('Y-m-d H:i:s',$data[$i-2]['create_time']));
        }


        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.'信息'.'.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }

    /**
     * 说明文档
     * @return [type] [description]
     */
    public function doc(){
        # 开发或维护各种内容管理后台 将数据做成报表

        # php版本不能太低，现阶段需要5.6+
    }
}
